$(document).ready(function() {
	menuSelect('queryDB');
	var contextPath = $('#contextPath').val();
	$.ajaxSetup({
		type: "POST",
		url: contextPath + "/QueryDBServlet",
		dataType: "json"
	});
	$('body').ajaxError(function (event, xhr, settings, error) {
		if (error)
			alert(error);
		else if (xhr.status == 500 && xhr.getResponseHeader('Content-Type') == 'text/plain')
			alert('Got Error From Server:\n' + xhr.responseText);
		else
			alert('Got Error From Server:\n' + xhr.status + ' - ' + xhr.statusText);
	});
	$('body').ajaxStart(function() {
		$('#divAjaxOverlay').show();
	});
	$('body').ajaxStop(function() {
		$('#divAjaxOverlay').hide();
	});
	// Preview query
	$('#query').simpleautogrow();
	$('#btnPreviewQuery').click(previewQuery);
	$('#btnNextToIpGeo').attr('disabled', true);
	$('#btnNextToIpGeo').click(function() {
		$('#divPreviewQuery').hide();
		$('#divIpGeo').show();
	});
	$('#ddlQueryName').change(function() {
		if ($('#ddlQueryName').val() == '')
		{			
			return;
		}
		
		var lastSelectedQuery = $('#selectedQuery').val();
		var newSelectedQuery = $('#ddlQueryName').val();
		
		if (lastSelectedQuery && (lastSelectedQuery == newSelectedQuery))
		{
			return;
		}
		
		if ($('#query').val() != '')
		{
			if (!confirm('Query text box is not empty. Loading the query will overridre the data. Continue?'))
			{
				$('#ddlQueryName').val(lastSelectedQuery);
				return;
			}
		}
		
		loadQuery();
	});
	// Preview ip geo
	$('#ipColumn').change(function() {
		var ipColumn = $('#ipColumn').val();
		if (ipColumn == '')
			return;
		else
		{
			$('#ipColumn option[value=\'\']').remove();
			$('#btnPreviewIpGeo').removeAttr('disabled');
		}
	});
	$('#btnPreviewIpGeo').click(previewIpGeo);
	$('#btnNextToFieldSelect').attr('disabled', true);
	$('#btnPreviewIpGeo').attr('disabled', true);
	$('#btnBackToPreviewQuery').click(function() {
		$('#divIpGeo').hide();
		$('#divPreviewQuery').show();
	});
	$('#btnNextToFieldSelect').click(function() {
		$('#divIpGeo').hide();
		$('#divFieldSelect').show();
	});
	// Field select
	$('#btnBackToIpGeo').click(function() {
		$('#divFieldSelect').hide();
		$('#divIpGeo').show();
	});
	$('#btnSaveResults').click(saveResults);
	$('#btnSaveQuery').click(saveQuery);
	$('#traceColumn').change(function() {
		var traceColumn = $('#traceColumn').val();
		if (traceColumn == '')
			return;
		else
		{
			$('#traceColumn option[value=\'\']').remove();
			$('#btnSaveResults').removeAttr('disabled');
		}
	});
	$("#progressBar").progressbar({ value: 0 });
	$("#progressBar").hide();
});

function previewQuery() {
	var server = $('#serverName').val();
	var query = $('#query').val();
	var previewRows = $('#previewRows').val();
	
	if (query == '') {
		alert('Please enter a valid SQL query.');
		return false;
	}
	
	$.ajax({
		data: { 
			"action": "previewQuery",
			"server": server,
			"query": query,
			"previewRows": previewRows
		},
		beforeSend: function() {
			$('#btnPreviewQuery').attr('disabled', true);
		},
		success: function(jsonTable) {
	    	$('#divQueryResults').html("");
	    	var table = tableFromJSON(jsonTable);
	    	$('#divQueryResults').append(table);
	    	var lastIpColumnText = $('#ipColumn :selected').text();
	    	var lastIpColumnFound = false;
	    	$('#ipColumn').empty();
	    	var lastTraceColumnText = $('#traceColumn :selected').text();
	    	var lastTraceColumnFound = false;
	    	$('#traceColumn').empty();
	    	$.each(jsonTable.columns, function(i, cname) {
	    		$('#ipColumn').append(
		    			$('<option>').val(i).text(cname)
	    		);
	    		if (cname.toLowerCase() == lastIpColumnText.toLowerCase()) {
	    			$('#ipColumn').val(i);
	    			lastIpColumnFound = true;
	    		};
	    		$('#traceColumn').append(
		    			$('<option>').val(i).text(cname)
	    		);
	    		if (cname.toLowerCase() == lastTraceColumnText.toLowerCase()) {
	    			$('#ipColumn').val(i);
	    			lastTraceColumnFound = true;
	    		};
	    	});
	    	if (!lastIpColumnFound) {
		    	$('#ipColumn').prepend($('<option>').val("").text("Please select"));
		    	$('#ipColumn').val("");
	    	};
	    	if (!lastTraceColumnFound) {
		    	$('#traceColumn').prepend($('<option>').val("").text("Please select"));
		    	$('#traceColumn').val("");
	    	};
	    	$('#btnNextToIpGeo').removeAttr('disabled');
	   	},
	   	error: function(data) {
	   		$('#btnNextToIpGeo').attr('disabled', true);
	   	},
	   	complete: function() {
	   		$('#btnPreviewQuery').removeAttr('disabled');
	   	}
	});
}

function previewIpGeo() {
	var server = $('#serverName').val();
	var query = $('#query').val();
	var previewRows = $('#previewRows').val();
	var ipColumn = $('#ipColumn').val();
	
	if (query == '') {
		alert('Please enter a valid SQL query.');
		return false;
	}
	
	if (ipColumn == '') {
		alert('Please select an IP column.');
		return false;
	}
	
	$.ajax({
		data: { 
			"action": "previewIpGeo",
			"server": server,
			"query": query,
			"previewRows": previewRows,
			"ipColumn": ipColumn
		},
		beforeSend: function() {
			$('#btnPreviewIpGeo').attr('disabled', true);
		},
		success: function(jsonTable) {
	    	$('#divQueryResults').html("");
	    	var table = tableFromJSON(jsonTable);
	    	$('#divQueryResults').append(table);
	    	$('#btnNextToFieldSelect').removeAttr('disabled');
	   	},
	   	error: function(data) {
	   		$('#btnNextToFieldSelect').attr('disabled', true);
	   	},
	   	complete: function() {
	   		$('#btnPreviewIpGeo').removeAttr('disabled');
	   	}
	});
}

function saveResults() {
	var server = $('#serverName').val();
	var query = $('#query').val();
	var ipColumn = $('#ipColumn').val();
	var traceColumn = $('#traceColumn').val();
	var filename = $('#resultsFilename').val();
	var maxRows = $('#maxRows').val();
	var requestID = randomString();
	var timerID = -1;
	
	if (query == '') {
		alert('Please enter a valid SQL query.');
		return false;
	}
	
	if (ipColumn == '') {
		alert('Please select an IP column.');
		return false;
	}
	
	if (traceColumn == '') {
		alert('Please select a trace column.');
		return false;
	}
	
	if (filename == '') {
		alert('Please enter a valid file name.');
		return false;
	}
	
	if (maxRows == '') {
		alert('Please enter maximum number of rows.');
		return false;
	}
		
	progressBarUpdate = function() {
		$.ajax({
			data: {
				"action": "queryProgress",
				"requestID": requestID
			},
			success: function(json) {
				if (json.success) {
					$("#progressBar").progressbar( "value" , json.progress );
				}
			},
			error: function() {
				
			}
		});
	};
	
	$.ajax({
		data: { 
			"action": "saveResults",
			"server": server,
			"query": query,
			"ipColumn": ipColumn,
			"traceColumn": traceColumn,
			"filename": filename,
			"maxRows": maxRows,
			"requestID": requestID
		},
		beforeSend: function() {
			$('#btnSaveResults').attr('disabled', true);
			$('#loadingImage').hide();
			$("#progressBar").progressbar( "value" , 0 );
			$("#progressBar").show();
			timerID = setInterval(progressBarUpdate, 1000);			
		},
		success: function(json) {
			$("#progressBar").progressbar( "value" , 100 );
	    	alert('Results saved successfully. Rows processed: ' + json.rows);
	   	},
	   	error: function(data) {
	   		//$('#btnNextToFieldSelect').attr('disabled', true);
	   	},
	   	complete: function() {
	   		clearInterval(timerID);
			$('#loadingImage').show();
			$("#progressBar").hide();
	   		$('#btnSaveResults').removeAttr('disabled');
	   	}
	});
}

function saveQuery() {
	var server = $('#serverName').val();
	var query = $('#query').val();
	var previewRows = $('#previewRows').val();
	var ipColumn = $('#ipColumn').val();
	var traceColumn = $('#traceColumn').val();
	var filename = $('#queryFilename').val();
	var maxRows = $('#maxRows').val();
	
	if (query == '') {
		alert('Please enter a valid SQL query.');
		return false;
	}
	
	if (ipColumn == '') {
		alert('Please select an IP column.');
		return false;
	}
	
	if (traceColumn == '') {
		alert('Please select a trace column.');
		return false;
	}
	
	if (filename == '') {
		alert('Please enter a valid file name.');
		return false;
	}
	
	$.ajax({
		data: { 
			"action": "saveQuery",
			"server": server,
			"query": query,
			"previewRows": previewRows,
			"ipColumn": $('#ipColumn :selected').text(),
			"traceColumn": $('#traceColumn :selected').text(),
			"filename": filename,
			"maxRows": maxRows
		},
		beforeSend: function() {
			$('#btnSaveQuery').attr('disabled', true);
		},
		success: function(json) {
	    	alert('Query saved successfully.');
	   	},
	   	error: function(data) {
	   		//$('#btnNextToFieldSelect').attr('disabled', true);
	   	},
	   	complete: function() {
	   		$('#btnSaveQuery').removeAttr('disabled');
	   	}
	});	
}

function loadQuery() {
	var queryName = $('#ddlQueryName').val();
	$.ajax({
		data: { 
			"action": "loadQuery",
			"queryName": queryName					
		},
		error: function(data) {
			$('#ddlQueryName').val($('#selectedQuery').val());
			return true;
	   	},
		success: function(json) {
	   		$('#query').val(json.query);
	   		$('#divQueryResults').html("");
	   		$('#serverName').val(json.server);
	   		$('#previewRows').val(json.previewRows);
	   		$('#btnNextToIpGeo').attr('disabled', true);
	    	$('#ipColumn').empty();
    		$('#ipColumn').append(
	    		$('<option>').val("").text(json.ipColumnText)
    		);
    		$('#btnPreviewIpGeo').removeAttr('disabled');
	    	$('#traceColumn').empty();
    		$('#traceColumn').append(
	    		$('<option>').val("").text(json.traceColumnText)
    		);
    		$('#maxRows').val(json.maxRows);
    		$('#ddlQueryName option[value=\'\']').remove();
    		$('#selectedQuery').val($('#ddlQueryName').val());
    		$('#queryFilename').val($('#ddlQueryName :selected').text());
	   	}
	});	
}

function tableFromJSON(jsonTable) {
	var table = $('<table>');

	var trHeader = $('<tr>');
	table.append(trHeader);
	$.each(jsonTable.columns, function(i, cname) {
		var th = $('<th>');
		th.text(cname);
		trHeader.append(th);
	});
	
	$.each(jsonTable.rows, function(i, row) {
		var tr = $('<tr>');
		table.append(tr);
		$.each(row, function(j, item) {
			var td = $('<td>');
			td.text(item);
			tr.append(td);
		});
	});
	
	return table;
}

function randomString() {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 16;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}